package socket

import (
	"encoding/binary"
	"fmt"
	"net"
	"strconv"

	"go.uber.org/zap"
)

type TcpServer struct {
	listener       net.Listener
	endian         binary.ByteOrder
	connectHandler ConnectHandler
	active         bool
}

func (t *TcpServer) Start(port int, bufferSize int, endian binary.ByteOrder, connectHandler ConnectHandler) {
	listener, err := net.Listen("tcp", "0.0.0.0:"+strconv.Itoa(port))
	if err != nil {
		return
	}
	t.listener = listener
	t.endian = endian
	t.connectHandler = connectHandler
	t.active = true
	go t.listen()
}

func (t *TcpServer) Stop() {
	t.active = false
	t.listener.Close()
}

func (t *TcpServer) listen() {
	for t.active {
		conn, err := t.listener.Accept()
		if err != nil {
			zap.L().Info(fmt.Sprint("Accept err = ", err))
		} else {
			zap.L().Info(fmt.Sprintf("Accept suc con = %v, 客户端IP = %v\n", conn, conn.RemoteAddr().String()))
			connectContext := NewContext(conn, t.endian, t.connectHandler)
			go connectContext.process()
		}
	}
}
